package com.zhongxi.guoyuan.view.personalCenter;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.navisdk.adapter.BNCommonSettingParam;
import com.baidu.navisdk.adapter.BNOuterLogUtil;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.yanzhenjie.permission.AndPermission;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.coinShop.CoinPostGoodAttrAdapter;
import com.zhongxi.guoyuan.adapter.personCenter.ClearEvaluateAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.clearweed.ClearEvaluateResult;
import com.zhongxi.guoyuan.entity.clearweed.ClearPayResult;
import com.zhongxi.guoyuan.entity.clearweed.ClearWeedDetailResult;
import com.zhongxi.guoyuan.entity.coinPost.LogisiticsData;
import com.zhongxi.guoyuan.entity.coinStore.AttrItemBean;
import com.zhongxi.guoyuan.entity.coinStore.AttrsSelect;
import com.zhongxi.guoyuan.entity.coinStore.GoodsAttrCollections;
import com.zhongxi.guoyuan.entity.coinStore.RewardCoinDetailData;
import com.zhongxi.guoyuan.entity.pay.PayAliPayData;
import com.zhongxi.guoyuan.entity.pay.WeixinData;
import com.zhongxi.guoyuan.entity.user.center.UserExtendResult;
import com.zhongxi.guoyuan.fragment.clearweeddetail.ClearweedCommentFragment;
import com.zhongxi.guoyuan.fragment.clearweeddetail.ClearweedDetailFragment;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.DesTool;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.MD5Tool;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.utils.PayUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.MapNaviActivity;
import com.zhongxi.guoyuan.view.PaySuccessActivity;
import com.zhongxi.guoyuan.view.beautifulStore.ProjectDetailActivity;
import com.zhongxi.guoyuan.view.beautifulStore.StoreDetailActivity;
import com.zhongxi.guoyuan.view.rewardCoin.ApplyRewardActivity;
import com.zhongxi.guoyuan.view.rewardCoin.RewardCoinDetailActivity;
import com.zhongxi.guoyuan.widget.MyListView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;
import com.zhongxi.guoyuan.zhifubao.PayResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.File;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClearWeedDetailActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.rl)
    RelativeLayout rl;
    @Bind(R.id.clearWeed_detail_share)
    LinearLayout clearWeedDetailShare;
    @Bind(R.id.clearWeed_detail_pay)
    RelativeLayout clearWeedDetailPay;
    @Bind(R.id.linear_bottom)
    LinearLayout linearBottom;
    @Bind(R.id.clearWeed_detail_banner)
    Banner clearWeedDetailBanner;
    @Bind(R.id.clearWeed_detail_name)
    TextView clearWeedDetailName;
    @Bind(R.id.clearWeed_detail_original)
    TextView clearWeedDetailOriginal;
    @Bind(R.id.clearWeed_detail_sales)
    TextView clearWeedDetailSales;
    @Bind(R.id.clearWeed_detail_exchangeTip)
    TextView clearWeedDetailExchangeTip;
    @Bind(R.id.clearWeed_detail_beanNum)
    TextView clearWeedDetailBeanNum;
    @Bind(R.id.clearWeed_detail_redbean)
    TextView clearWeedDetailRedBean;
    @Bind(R.id.clearWeed_detail_stock)
    TextView clearWeedDetailStock;
    @Bind(R.id.clearWeed_detail_line)
    View clearWeedDetailLine;
    @Bind(R.id.clearWeed_detail_declare)
    TextView clearWeedDetailDeclare;
    @Bind(R.id.clearWeed_detail_limit)
    TextView clearWeedDetailLimit;
    @Bind(R.id.clearWeed_detail_content)
    TextView clearWeedDetailContent;
    @Bind(R.id.subscrib_address_tip)
    TextView subscribAddressTip;
    @Bind(R.id.iv_goshopping)
    ImageView ivGoshopping;
    @Bind(R.id.clearWeed_detail_shopName)
    TextView clearWeedDetailShopName;
    @Bind(R.id.clearWeed_detail_call)
    TextView clearWeedDetailCall;
    @Bind(R.id.iv_phone)
    ImageView ivPhone;
    @Bind(R.id.clearWeed_detail_shopPhone)
    TextView clearWeedDetailShopPhone;
    @Bind(R.id.iv_position)
    ImageView ivPosition;
    @Bind(R.id.clearWeed_detail_navigation)
    TextView clearWeedDetailNavigation;
    @Bind(R.id.clearWeed_detail_shopAddress)
    TextView clearWeedDetailShopAddress;
    @Bind(R.id.clearWeed_detail_scrollView)
    MyScrollView clearWeedDetailScrollView;
    @Bind(R.id.tv_clearDetail_evaluate)
    TextView tvEvaluate;
    @Bind(R.id.clearweed_detail_postage)
    TextView postage;
    @Bind(R.id.clearweed_detail_btComment)
    TextView btComment;
    @Bind(R.id.clearweed_detail_btDetail)
    TextView btDetail;
    @Bind(R.id.clearweed_detail_relaContainer)
    RelativeLayout relaContainer;
    ClearWeedDetailResult detailResult;
    List<String> imageList;
    private ClearWeedDetailResult.GoodsInfoBean goodsInfo;
    private ClearWeedDetailResult.ShopInfoBean shopInfo;
    private static int REQUEST_CODE = 1000;
    private String phone;
    private View popupWindow_view;
    private PopupWindow popupWindow;
    private SHARE_MEDIA platform;
    private EditText etNum;
    private EditText exist;
    private String trim;
    private TextView price;
    private TextView tvRedBean;
    private int purchasingnum;
    private String type;
    private UserExtendResult extendResult;
    private String passWord;

    private String id;

    int num = 1;//商品数量
    int totalPrice;//商品总美豆
    int totalRedBean;//商品总红豆数
    private ClearPayResult payResult;
    private ClearEvaluateAdapter evaluateAdapter;
    private JSONObject user;
    private AlertDialog dialog;
    private int score;
    private EditText editText;
    private String payResultOrderid;
    private String evaluateContent;
    private BaseResponse baseResponse;

    private static final String APP_FOLDER_NAME = "Meirongyuan";
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    private String mSDCardPath = null;
    public static List<Activity> activityList = new LinkedList<Activity>();

    private final static String authBaseArr[] =
            {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION};

    private final static String authComArr[] = {Manifest.permission.READ_PHONE_STATE};
    private int authComRequestCode = 2;
    private final static int authBaseRequestCode = 1;
    private boolean hasRequestComAuth = false;

    private ProgressDialog progressDialog;

    private List<GoodsAttrCollections> attrCollectionses;
    private JSONObject attr;
    private List<List<AttrItemBean>> itemAttrList;
    private Map<String, List<AttrItemBean>> mapAllAttrs;
    private CoinPostGoodAttrAdapter coinPostGoodAttrAdapter;
    private boolean isSameAttrKey;
    private ArrayList<String> attrKeyList;
    private Map<String, List<String>> maps;
    private ArrayList<AttrsSelect> allList;
    private ImageView ivImg;
    private TextView tvInventory;
    private TextView tv_price;
    private TextView tv_redprice;
    private TextView text_collect;

    boolean stateType1, stateType2, stateType3;  //同城,自提,邮寄

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的一部通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();//同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //判断resultStatus为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //该笔订单是否真实支付成功，需要依赖服务端的异步通知
//                        Intent intent = new Intent(context, PaySuccessActivity.class);
//                        intent.putExtra("status", 1);
//                        startActivity(intent);
                        showShortToast("支付成功");
                        showEvaluateDialog();
                    } else {
                        showShortToast("支付失败");
                        startAct(PaySuccessActivity.class);
                    }
                    break;
            }
        }
    };

    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {
        }

        @Override
        public void playStart() {
        }
    };
    private int trueMoney;
    private int trueRedBean;
    private PayAliPayData aliPayData;
    private WeixinData weixinData;
    private String goodsInfoName;

    private ClearweedCommentFragment mCommentFragment;
    private ClearweedDetailFragment mDetailFragment;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_clear_weed_detail);
        ButterKnife.bind(this);
        tvTitle.setText("豆豆兑换商品详情");
        initBanner();
        ImageUtils.setHeight(this, Constants.flowRate, clearWeedDetailBanner);

        initFragment();
    }

    private void initFragment() {

       mDetailFragment=new ClearweedDetailFragment();
       mCommentFragment=new ClearweedCommentFragment(id);

       fragments=new android.support.v4.app.Fragment[]{mDetailFragment,mCommentFragment};

        btDetail.setSelected(true);
        btComment.setSelected(false);

        getSupportFragmentManager().beginTransaction().add(R.id.clearweed_detail_relaContainer,mDetailFragment).commit();
    }

    private void initBanner() {
        clearWeedDetailBanner.isAutoPlay(true);
        clearWeedDetailBanner.setDelayTime(3000);
        clearWeedDetailBanner.setIndicatorGravity(BannerConfig.CENTER);
    }

    @Override
    protected void initData() {
        super.initData();
        id = getIntent().getStringExtra("id");
        getDetailData();
        imageList = new ArrayList<>();
    }

    /***
     * 获取详细信息
     */
    private void getDetailData() {
        type = "detail";
        String str = "&gid=" + id;
        getServer(Url.CLEARWEED_DETAIL, null, str, false, null, "get");
    }


    /***
     * 获取校验码
     */
    private void topayVerifyCode() {
        type = "verifyCode";
        getServer(Url.MY_EXTEND_INFO, null, "", false, null, "get");
    }

    /***
     * 发起支付
     * @param verifycode
     */
    private void topay(String verifycode) {
        type = "pay";
        Map<String, String> map = new HashMap<>();
        map.put("pwd", MyApplication.getInstance().descsc(passWord));
        map.put("verifycode", verifycode);
        map.put("shopid", goodsInfo.getShopid());
        map.put("goodsid", goodsInfo.getId());
        map.put("goodsnum", num + "");
        map.put("innerprice", (Integer.parseInt(goodsInfo.getInnerprice()) * num) + "");
        map.put("redbean", trueRedBean + "");
        map.put("price", trueMoney + "");
//        map.put("price",(Integer.parseInt(goodsInfo.getInnerprice()) * num) + "");

        for (String kay : map.keySet()) {
            Log.d("flag", "topay: " + kay + ":::" + map.get(kay));
        }
        getServer(Url.CLEARWEED_PAY, map, "", false, null, "post");
    }

    /**
     * 添加评价
     */
    private void toEvaluate() {
        type = "addevaluate";
        Map<String, String> map = new HashMap<>();
        map.put("shopid", goodsInfo.getShopid());
        map.put("orderid", payResultOrderid);
        map.put("goodsid", goodsInfo.getId());
        map.put("starlevel", score + "");
        map.put("content", evaluateContent);
        getServer(Url.CLEARWEED_ADDEVALUATE, map, "", false, null, "post");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        clearWeedDetailScrollView.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {

            }

            @Override
            public void scrollBottom() {

            }
        });
    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        if (type.equals("detail")) {
            detailResult = gson.fromJson(response, ClearWeedDetailResult.class);
            MyApplication.getInstance().setSpValue(detailResult.getSafeobj());


            if (null != detailResult && !"".equals(detailResult)) {
                goodsInfo = detailResult.getGoodsInfo();
                shopInfo = detailResult.getShopInfo();
                purchasingnum = detailResult.getPurchasingnum();
                if (null != goodsInfo && !"".equals(goodsInfo)) {
                    initGoodsInfo(goodsInfo);
                }
                if (null != shopInfo && !"".equals(shopInfo)) {
                    initShopInfo(shopInfo);
                }
            }
            
            if (detailResult.getGoodsAttrCollection() != null && !"".equals(detailResult.getGoodsAttrCollection())) {
                attrCollectionses = detailResult.getGoodsAttrCollection();
            }

            JSONObject jsonObject = new JSONObject(response);
            attr = jsonObject.optJSONObject("attrList");
            JSONArray attrKeyjson = jsonObject.optJSONArray("attrKey");//  "["汽车型号","形状","汽油型号","汽车牌照"]"
            attrKeyList = new ArrayList<>();
            for (int i = 0; i < attrKeyjson.length(); i++) {
                String e = (String) attrKeyjson.get(i);
                attrKeyList.add(e);
            }
            maps = new HashMap<>();
            if (attr != null && !"".equals(attr)) {
                Iterator<String> keys = attr.keys();
                while (keys.hasNext()) {
                    String next = keys.next();
                    JSONArray jsonArray = attr.optJSONArray(next);
                    List<String> attrIdList = new ArrayList<>();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        try {
                            JSONArray jsonArray1 = (JSONArray) jsonArray.get(i);
                            for (int j = 0; j < jsonArray1.length(); j++) {
                                if (j == 1) {
                                    String attrid = (String) jsonArray1.get(1);
                                    attrIdList.add(attrid);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    maps.put(next, attrIdList);
                }
            }
            allList = new ArrayList<>();
            JSONArray jsonArray2 = jsonObject.optJSONArray("goodsAttrCollection");
            for (int i = 0; i < jsonArray2.length(); i++) {
                JSONObject jsonObject1 = (JSONObject) jsonArray2.get(i);
                AttrsSelect attrsSelect = new AttrsSelect();
                String price = jsonObject1.optString("innerprice");
                String redprice =jsonObject1.optString("redbean");
                String thumbnail = jsonObject1.optString("thumbnail");
                String goodsid = jsonObject1.optString("goodsid");
                String id = jsonObject1.optString("id");
                String stocknum = jsonObject1.optString("stocknum");
                JSONObject object = jsonObject1.optJSONObject("newattr");
                Map<String, List<String>> itemAttrMap = new HashMap<>();
                if (object != null && !"".equals(object)) {
                    Iterator<String> keys = object.keys();
                    while (keys.hasNext()) {
                        String next = keys.next();
                        JSONArray jsonArray = object.optJSONArray(next);
                        List<String> attr = new ArrayList<>();
                        if (jsonArray != null && jsonArray.length() > 0) {
                            for (int j = 0; j < jsonArray.length(); j++) {
                                attr.add((String) jsonArray.get(j));
                            }
                            itemAttrMap.put(next, attr);
                        }
                    }
                }
                attrsSelect.setPrice(price);
                attrsSelect.setRedprice(redprice);
                attrsSelect.setThumbnail(thumbnail);
                attrsSelect.setItemMaps(itemAttrMap);
                attrsSelect.setGoodsid(goodsid);
                attrsSelect.setId(id);
                attrsSelect.setStocknum(stocknum);
                attrsSelect.setShopName(detailResult.getShopInfo().getName());
                attrsSelect.setShopId(detailResult.getShopInfo().getId());
                attrsSelect.setPhone(detailResult.getShopInfo().getPhone());
                attrsSelect.setAddress(detailResult.getShopInfo().getAddress());
                attrsSelect.setAmountofmail(detailResult.getShopInfo().getAmountofmail());
                allList.add(attrsSelect);
            }
            
        } else if (type.equals("verifyCode")) {
            extendResult = gson.fromJson(response, UserExtendResult.class);
            MyApplication.getInstance().setSpValue(extendResult.getSafeobj());
            if (null != extendResult.getVerifycode() && !"".equals(extendResult.getVerifycode())) {
                topay(extendResult.getVerifycode());
            } else {
                showShortToast("支付校验失败");
            }
        } else if (type.equals("pay")) {
            payResult = gson.fromJson(response, ClearPayResult.class);
            MyApplication.getInstance().setSpValue(payResult.getSafeobj());
            if (null != payResult && !"".equals(payResult)) {
                payResultOrderid = payResult.getOrderid();
                popupWindow.dismiss();
                String securityKey = payResult.getSecurityKey();
                if (null != securityKey && !"".equals(securityKey)) {
                    String payParams = parseSecutiryKey(securityKey);
                    try {
                        JSONObject jsonObject = new JSONObject(payParams);
                        JSONObject alipay = jsonObject.optJSONObject("alipay");
                        aliPayData = PayAliPayData.parseObject(alipay);
                        JSONObject wechat = jsonObject.optJSONObject("wechat");
                        weixinData = WeixinData.parseObject(wechat);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    MyApplication.getInstance().sharedPrefrences.edit().putString("pay", "exchange").commit();
                    showHongdouNoBalance();
                } else {
                    showEvaluateDialog();
                }
            }
        } else if (type.equals("addevaluate")) {
            baseResponse = gson.fromJson(response, BaseResponse.class);
            MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
            dialog.dismiss();
            showShortToast("感谢您的评价");
            startAct(MainHomeActivity.class);
            finish();
        }
    }

    /***
     * 评价
     */
    private void showEvaluateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(context).inflate(R.layout.clearweed_evaluate, null);
        builder.setView(view);
        dialog = builder.create();
        dialog.setCancelable(false);
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
        ImageView ivCancel = (ImageView) view.findViewById(R.id.dialog_evaluate_cancel);
        editText = (EditText) view.findViewById(R.id.dialog_evaluate_content);
        final TextView textNum = (TextView) view.findViewById(R.id.dialog_evaluate_textNum);
        TextView payCanael = (TextView) view.findViewById(R.id.dialog_evaluate_paycancel);
        TextView paySure = (TextView) view.findViewById(R.id.dialog_evaluate_paysure);
        RatingBar ratingBar = (RatingBar) view.findViewById(R.id.dialog_evaluate_ratingBar);

        ivCancel.setOnClickListener(this);
        payCanael.setOnClickListener(this);
        paySure.setOnClickListener(this);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                MyTextUtils.TextChangeUtils(ClearWeedDetailActivity.this, textNum, editable, 200);
            }
        });

        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
                score = (int) ratingBar.getRating();
            }
        });
    }

    /**
     * 红豆余额不足
     */
    private void showHongdouNoBalance() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_order_hongdou, null);
        final android.support.v7.app.AlertDialog dialog = new android.support.v7.app.AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView order_tvLess_hongdou = (TextView) layout.findViewById(R.id.order_tvLess_hongdou);
        order_tvLess_hongdou.setText(trueMoney + " 红豆");
        TextView order_tvLess_yuan = (TextView) layout.findViewById(R.id.order_tvLess_yuan);
        order_tvLess_yuan.setText(trueMoney + " 元");
        LinearLayout ll_aliPay = (LinearLayout) layout.findViewById(R.id.ll_aliPay);
        ll_aliPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CommonTool.isFirstLongScroll()) {
                    zhifubaoPayRequest(aliPayData);  //支付宝
                }
                dialog.dismiss();
            }
        });
        LinearLayout ll_weichatPay = (LinearLayout) layout.findViewById(R.id.ll_weichatPay);
        ll_weichatPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CommonTool.isFirstLongScroll()) {
                    weixinPayRequest(weixinData);  //微信支付
                }
                dialog.dismiss();
            }
        });
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        //放弃支付
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });

    }

    public void zhifubaoPayRequest(PayAliPayData alipay) {
        PayUtils payUtils = new PayUtils(payResultOrderid, goodsInfoName, 6, (Integer.parseInt(goodsInfo.getInnerprice()) * num) + "", trueRedBean + "", trueMoney + "");
        payUtils.zhifubaoPay(alipay, mHandler, ClearWeedDetailActivity.this);
    }

    private boolean jumpWxResult=false;
    public void weixinPayRequest(WeixinData weixinData) {
        PayUtils payUtils=new PayUtils(payResultOrderid,goodsInfoName,6,(Integer.parseInt(goodsInfo.getInnerprice()) * num) + "",trueRedBean + ""
                ,DataUtil.formatData(trueMoney+""),this,weixinData);
        payUtils.weixinPay();
        jumpWxResult=true;
    }

    /**
     * 解析后台返回的支付商户信息
     *
     * @param securityKey
     */
    private String parseSecutiryKey(String securityKey) {
        String jsonStr = "";
        try {
            String sourcestr = MD5Tool.Md5(MyApplication.getInstance().getSk() + MyApplication.getInstance().getNow());
            String strs = URLDecoder.decode(securityKey, "UTF-8");
            jsonStr = DesTool.splitdecode(sourcestr, strs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonStr;
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
        MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
        if (baseResponse.getCode() == 1000) {
            showShortToast("参数错误");
        } else if (baseResponse.getCode() == 1001) {
            showShortToast("用户未登录");
        } else if (baseResponse.getCode() == 1201) {
            showShortToast("店铺已关闭");
            finish();
        } else if (baseResponse.getCode() == 1202) {
            showShortToast("商品数量超出每日限额");
        } else if (baseResponse.getCode() == 2001) {
            showShortToast("库存不足");
        } else if (baseResponse.getCode() == 1691) {
            showShortToast("商品已下架");
            finish();
        } else if (baseResponse.getCode() == 4003) {
            showShortToast("密码错误");
        } else if (baseResponse.getCode() == 5003) {
            showShortToast("美豆不足");
        }
    }

    /***
     * 设置店铺信息
     * @param shopInfo
     */
    private void initShopInfo(ClearWeedDetailResult.ShopInfoBean shopInfo) {
        if (null != shopInfo.getName() && !"".equals(shopInfo.getName())) {
            clearWeedDetailShopName.setText(shopInfo.getName());
        } else {
            clearWeedDetailShopName.setText("");
        }
        if (null != shopInfo.getPhone() && !"".equals(shopInfo.getPhone())) {
            clearWeedDetailShopPhone.setText(shopInfo.getPhone());
        } else {
            clearWeedDetailShopPhone.setText("");
        }
        if (null != shopInfo.getAddress() && !"".equals(shopInfo.getAddress())) {
            clearWeedDetailShopAddress.setText(shopInfo.getAddress());
        } else {
            clearWeedDetailShopAddress.setText("");
        }
    }

    /***
     * 设置商品信息
     * @param goodsInfo
     */
    private void initGoodsInfo(ClearWeedDetailResult.GoodsInfoBean goodsInfo) {

        if (null != goodsInfo.getName() && !"".equals(goodsInfo.getName())) {
            goodsInfoName = goodsInfo.getName();
            clearWeedDetailName.setText(goodsInfoName);
        } else {
            clearWeedDetailName.setText("");
        }
        if(null!=goodsInfo.getPostage()&&"0".equals(goodsInfo.getPostage())){
            postage.setVisibility(View.VISIBLE);
        }else{
            postage.setVisibility(View.GONE);
        }
        if (null != goodsInfo.getMarketprice() && !"".equals(goodsInfo.getMarketprice())) {
            clearWeedDetailOriginal.setText("原价：" + goodsInfo.getMarketprice() + "元");
            clearWeedDetailOriginal.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        } else {
            clearWeedDetailOriginal.setText("");
        }
        if (null != goodsInfo.getOrdernum() && !"".equals(goodsInfo.getOrdernum())) {
            clearWeedDetailSales.setText("销量：" + goodsInfo.getOrdernum());
        } else {
            clearWeedDetailSales.setText("");
        }
        if (null != goodsInfo.getInnerprice() && !"".equals(goodsInfo.getInnerprice())) {
            clearWeedDetailBeanNum.setText(goodsInfo.getInnerprice() + "美豆");
        } else {
            clearWeedDetailBeanNum.setText("");
        }
        if (null != goodsInfo.getRedbeanprice() && !"".equals(goodsInfo.getRedbeanprice())) {
            clearWeedDetailRedBean.setText(" + " + goodsInfo.getRedbeanprice() + "红豆");
            totalRedBean = Integer.parseInt(goodsInfo.getRedbeanprice());
        } else {
            clearWeedDetailRedBean.setText("");
        }
        if (null != goodsInfo.getLaststocknum() && !"".equals(goodsInfo.getLaststocknum())) {
            clearWeedDetailStock.setText("库存：" + goodsInfo.getLaststocknum());
        } else {
            clearWeedDetailStock.setText("");
        }
        if (null != goodsInfo.getDaylimit() && !"".equals(goodsInfo.getDaylimit())) {
            clearWeedDetailLimit.setText("每天限" + goodsInfo.getDaylimit() + "份");
        } else {
            clearWeedDetailLimit.setText("");
        }
        if (null != goodsInfo.getSubject() && !"".equals(goodsInfo.getSubject())) {
            clearWeedDetailContent.setText(goodsInfo.getSubject());
        } else {
            clearWeedDetailContent.setText("");
        }
        if (null != goodsInfo.getImages() && !"".equals(goodsInfo.getImages())) {
            for (int i = 0; i < goodsInfo.getImages().size(); i++) {
                imageList.add(Url.IMG_URL + goodsInfo.getImages().get(i));
            }
            clearWeedDetailBanner.setImages(imageList).setImageLoader(new GlideImageLoader()).start();
        }
        if(null!=goodsInfo.getDesc()&&!"".equals(goodsInfo.getDesc())){
            mDetailFragment.ResultData(goodsInfo.getDesc());
        }
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        if (jumpWxResult)
       showEvaluateDialog();
    }


    @Override
    protected void onResume() {
        super.onResume();
                if (ContextCompat.checkSelfPermission(ClearWeedDetailActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(ClearWeedDetailActivity.this, Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(ClearWeedDetailActivity.this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(ClearWeedDetailActivity.this, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    ActivityCompat.requestPermissions(ClearWeedDetailActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.MODIFY_AUDIO_SETTINGS, Manifest.permission.INTERNET, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS}, 100);
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
//                            mapNavi();//初始化百度导航
                        }
                    }).start();
                }
    }

    @OnClick({R.id.ivBack, R.id.clearWeed_detail_share, R.id.clearWeed_detail_pay,
            R.id.clearWeed_detail_call, R.id.clearWeed_detail_navigation,R.id.tv_clearDetail_evaluate,
    R.id.clearweed_detail_btComment,R.id.clearweed_detail_btDetail})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                onBackPressed();
                break;
            case R.id.clearWeed_detail_share:
                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    initPopuWindow();
                }
                break;
            case R.id.clearWeed_detail_pay:
                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
//                    initPayWindow();
                    initAttrPopupWindow(1);
                }
                break;
            case R.id.clearWeed_detail_call:
                if (null != shopInfo.getPhone() && !"".equals(shopInfo.getPhone())) {
                    phone = shopInfo.getPhone();
                    requestCallphone(phone);
                }
                break;
            case R.id.tv_clearDetail_evaluate:
                Intent intent=new Intent(this,ClearWeedEvaluateActivity.class);
                intent.putExtra("id",id);
                startActivity(intent);
                break;
            case R.id.clearweed_detail_btDetail:

                btDetail.setSelected(true);
                btComment.setSelected(false);
                switchFragment(0);
                break;
            case R.id.clearweed_detail_btComment:

                btComment.setSelected(true);
                btDetail.setSelected(false);
                switchFragment(1);
                break;
            case R.id.clearWeed_detail_navigation://导航

                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(this);
                }
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);  //样式为圆形
                progressDialog.setCancelable(false);
                progressDialog.setOnKeyListener(keyListener);
                progressDialog.setMessage("正在获取数据,请稍后...");
                progressDialog.show();

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.MODIFY_AUDIO_SETTINGS, Manifest.permission.INTERNET, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS}, 100);
                } else {

                    mapNavi();//初始化百度导航

                    if (shopInfo.getLongitude() != null && shopInfo.getDimensions() != null) {

                        if (BaiduNaviManager.isNaviInited()) {
                            routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL);
                        } else {
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                        }
                    } else {
                        ToastUtil.show(getString(R.string.loseDataOfBaiduNavi));
                    }
                }
                break;
        }
    }

    private int currentIndex=0;
   private android.support.v4.app.Fragment[] fragments;
    private void switchFragment(int index) {

        if (index != currentIndex) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            if (fragments[currentIndex].isAdded()) {
                trx.hide(fragments[currentIndex]);
            }
            if (!fragments[index].isAdded()) {
                trx.add(R.id.clearweed_detail_relaContainer, fragments[index]);
            }
            trx.show(fragments[index]).commit();
            currentIndex = index;
        }
    }

    private DialogInterface.OnKeyListener keyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
            if (i == keyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }
            return false;
        }
    };

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            //Glide 加载图片简单用法
            Glide.with(context).load(path).placeholder(R.mipmap.iv_loading).into(imageView);
        }
    }
    
    

    //获取权限
    private void requestCallphone(String phone) {
        if (Build.VERSION.SDK_INT >= 23) {
            //判断有没有拨打权限
            if (PermissionChecker.checkSelfPermission(ClearWeedDetailActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE);
            } else {
                callPhone(phone);
            }
        } else {
            callPhone(phone);
        }
    }

    private void callPhone(String phone) {
        Uri uri = Uri.parse("tel:" + phone);
        Intent intent = new Intent(Intent.ACTION_DIAL, uri);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
            startActivity(intent);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE && PermissionChecker.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
            callPhone(phone);
        }
        if (requestCode == authBaseRequestCode) {
            for (int ret : grantResults) {
                if (ret == 0) {
                    continue;
                } else {
//                    Toast.makeText(StoreDetailActivity.this, "缺少导航基本的权限!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            initNavi();
        } else if (requestCode == authComRequestCode) {
            for (int ret : grantResults) {
                if (ret == 0) {
                    continue;
                }
            }
            routeplanToNavi(mCoordinateType);
        } else if (requestCode == 100) {
            mapNavi();//初始化百度导航
        }
    }


    private void initPayWindow() {
        popupWindow_view = getLayoutInflater().inflate(R.layout.clearweed_pay, null, false);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(clearWeedDetailPay, Gravity.BOTTOM, 0, 0);
        TextView tvSub = (TextView) popupWindow_view.findViewById(R.id.tvSub);
        etNum = (EditText) popupWindow_view.findViewById(R.id.etNum);
        TextView tvAdd = (TextView) popupWindow_view.findViewById(R.id.tvAdd);
        price = (TextView) popupWindow_view.findViewById(R.id.exchange_pay_price);
        tvRedBean = (TextView) popupWindow_view.findViewById(R.id.exchange_pay_redbean);
        TextView nowSave = (TextView) popupWindow_view.findViewById(R.id.exchange_pay_nowsave);
        exist = (EditText) popupWindow_view.findViewById(R.id.exchange_pay_existing);
        TextView cancel = (TextView) popupWindow_view.findViewById(R.id.exchange_pay_cancel);
        TextView sure = (TextView) popupWindow_view.findViewById(R.id.exchange_pay_sure);
        tvSub.setOnClickListener(this);
        tvAdd.setOnClickListener(this);
        cancel.setOnClickListener(this);
        sure.setOnClickListener(this);
        if (null != goodsInfo.getInnerprice() && !"".equals(goodsInfo.getInnerprice())) {
            price.setText(Integer.parseInt(goodsInfo.getInnerprice()) + "美豆");
        }
        if (null != goodsInfo.getRedbeanprice() && !"".equals(goodsInfo.getRedbeanprice())) {
            tvRedBean.setText(" + " + goodsInfo.getRedbeanprice() + "红豆");
        } else {
            tvRedBean.setText("");
        }
        nowSave.setText("您目前现存：" + MyApplication.getInstance().getInnerCurrency() + " 美豆/" + MyApplication.getInstance().getHdCurrency() + "红豆");

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvSub:
                trim = etNum.getText().toString().trim();
                num = Integer.parseInt(trim);
                if (num > 1) {
                    num--;
                }
                etNum.setText(num + "");
                if (null != goodsInfo && !"".equals(goodsInfo)) {
                    totalPrice = Integer.parseInt(goodsInfo.getInnerprice()) * num;
                    price.setText(totalPrice + "美豆");
                    if (goodsInfo.getRedbeanprice() != null) {
                        totalRedBean = Integer.parseInt(goodsInfo.getRedbeanprice()) * num;
                        tvRedBean.setText(" + " + totalRedBean + "红豆");
                    }
                }
                break;
            case R.id.tvAdd:
                trim = etNum.getText().toString().trim();
                num = Integer.parseInt(trim);
                num++;

                if (null != goodsInfo && !"".equals(goodsInfo)) {
                    if (num > Integer.parseInt(goodsInfo.getStocknum())) {
                        showShortToast("库存不足");
                        num--;
                    }
                    if ((purchasingnum + num) > Integer.parseInt(goodsInfo.getDaylimit())) {
                        showShortToast("商品数量超出每日限额");
                        num--;
                    }
                    etNum.setText(num + "");
                    totalPrice = Integer.parseInt(goodsInfo.getInnerprice()) * num;
                    price.setText(totalPrice + "美豆");
                    if (goodsInfo.getRedbeanprice() != null) {
                        totalRedBean = Integer.parseInt(goodsInfo.getRedbeanprice()) * num;
                        tvRedBean.setText(" + " + totalRedBean + "红豆");
                    }

                }
                break;
            case R.id.exchange_pay_cancel:
                popupWindow.dismiss();
                break;
            case R.id.exchange_pay_sure:
                passWord = exist.getText().toString().trim();

                if (!TextUtils.isEmpty(passWord)) {
                    if (Integer.parseInt(MyApplication.getInstance().getInnerCurrency()) < totalPrice) {
                        showShortToast("美豆不足");
                    } else {
                        if (Integer.parseInt(CommonTool.getWhole(MyApplication.getInstance().getHdCurrency())) < totalRedBean) {
                            trueMoney = Integer.parseInt(DataUtil.subtract(totalRedBean + "", CommonTool.getWhole(MyApplication.getInstance().getHdCurrency())));
                            trueRedBean = Integer.parseInt(CommonTool.getWhole(MyApplication.getInstance().getHdCurrency()));
                        } else {
                            trueMoney = 0;
                            trueRedBean = totalRedBean;
                        }

                        topayVerifyCode();
                    }
                } else {
                    showShortToast("请输入密码");
                }

                break;
            case R.id.dialog_evaluate_cancel:
                if (dialog != null) {
                    dialog.dismiss();
                }
                break;
            case R.id.dialog_evaluate_paycancel:
                editText.setText("");
                break;
            case R.id.dialog_evaluate_paysure:
                evaluateContent = editText.getText().toString().trim();
                if (score < 1) {
                    showShortToast("请选择您的评分");
                } else if (evaluateContent.equals("") || evaluateContent.length() < 1) {
                    showShortToast("请输入您的评价");
                } else {
                    toEvaluate();
                }

                break;
        }
    }

    boolean isRemove = false;

    private void initAttrPopupWindow(final int flag) {
        final Map<String, AttrItemBean> selectAttrMap = new HashMap<>();
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                AttrItemBean attrItemBean = (AttrItemBean) msg.getData().getSerializable("attrItemBean");
                String attrId = attrItemBean.getAttrId();
                for (String attrKey : maps.keySet()) {
                    List<String> list = maps.get(attrKey);
                    for (int i = 0; i < list.size(); i++) {
                        if (attrId.equals(list.get(i))) {  //找到相应的key
                            if (selectAttrMap != null) {
                                if (selectAttrMap.size() > 0) {
                                    Iterator<String> iterator = selectAttrMap.keySet().iterator();
                                    while (iterator.hasNext()) {
                                        String next = iterator.next();
                                        AttrItemBean mapValue = selectAttrMap.get(next);
                                        if (mapValue.getAttrId().equals(attrId)) {   //去除属性
                                            iterator.remove();
                                            isRemove = true;
                                            break;
                                        }
                                    }
                                    if (isRemove) {  //去除属性
                                        if (selectAttrMap.size() > 0) {
                                            if (selectAttrMap.size() == 1) {
                                                Map.Entry<String, AttrItemBean> next = selectAttrMap.entrySet().iterator().next();
                                                String key = next.getKey();
                                                AttrItemBean value = next.getValue();
                                                List<String> canAttrs = getOnlyOneAttrCanSelect(value, key);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, canAttrs, selectAttrMap);
                                                coinPostGoodAttrAdapter.notifyDataSetChanged();
                                                isRemove = false;
                                                getItemClickChangePic();
                                                return;
                                            } else {
                                                List<String> referList = getAllAlreadItemCanSelect(selectAttrMap);
                                                List<String> listStrings = getCompareStringList();
                                                referList.addAll(listStrings);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, referList, selectAttrMap);
                                                coinPostGoodAttrAdapter.notifyDataSetChanged();
                                                isRemove = false;
                                                getItemClickChangePic();
                                                return;
                                            }
                                        } else {  //无点击,恢复正常
                                            itemAttrList = DataUtil.updataAdapter(itemAttrList);
                                            coinPostGoodAttrAdapter.notifyDataSetChanged();
                                            selectAttrMap.clear();
                                            isRemove = false;
                                            getItemClickChangePic();
                                            return;
                                        }
                                    } else {  //不去除属性
                                        for (String selectKey : selectAttrMap.keySet()) {
                                            if (attrKey.equals(selectKey)) {  //同一类点击切换
                                                isSameAttrKey = true;
                                                break;
                                            }
                                        }
                                        if (isSameAttrKey) {  //同一类点击切换
                                            if (selectAttrMap.size() == 1) {
                                                selectAttrMap.clear();
                                                selectAttrMap.put(attrKey, attrItemBean);
                                                List<String> canAttrs = getOnlyOneAttrCanSelect(attrItemBean, attrKey);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, canAttrs, selectAttrMap);
                                                coinPostGoodAttrAdapter.notifyDataSetChanged();
                                                getItemClickChangePic();
                                                isSameAttrKey = false;
                                                return;
                                            } else {
                                                selectAttrMap.put(attrKey, attrItemBean);
                                                List<String> referList = getAllAlreadItemCanSelect(selectAttrMap);
                                                List<String> listStrings = getCompareStringList();
                                                referList.addAll(listStrings);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, referList, selectAttrMap);
                                                coinPostGoodAttrAdapter.notifyDataSetChanged();
                                                getItemClickChangePic();
                                                isSameAttrKey = false;
                                                return;
                                            }
                                        } else {  //不同类的属性点击
                                            selectAttrMap.put(attrKey, attrItemBean);
                                            List<String> referList = getAllAlreadItemCanSelect(selectAttrMap);
                                            List<String> listStrings = getCompareStringList();
                                            referList.addAll(listStrings);
                                            itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, referList, selectAttrMap);
                                            coinPostGoodAttrAdapter.notifyDataSetChanged();
                                            getItemClickChangePic();
                                            isSameAttrKey = false;
                                            return;
                                        }
                                    }
                                } else {
                                    selectAttrMap.put(attrKey, attrItemBean);
                                    List<String> canAttrs = getOnlyOneAttrCanSelect(attrItemBean, attrKey);
                                    itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, canAttrs, selectAttrMap);
                                    coinPostGoodAttrAdapter.notifyDataSetChanged();
                                    getItemClickChangePic();
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            @NonNull
            private List<String> getCompareStringList() {
                List<List<String>> compareOtherList = new ArrayList<>();
                for (String strKey : selectAttrMap.keySet()) {
                    Map<String, AttrItemBean> secordMap = new HashMap<>();
                    for (String secordKey : selectAttrMap.keySet()) {
                        if (!secordKey.equals(strKey)) {
                            secordMap.put(secordKey, selectAttrMap.get(secordKey));
                        }
                    }
                    List<String> secordItemList = getAllAlreadItemCanSelect(secordMap);
                    List<String> singleList = getSingleList(strKey);
                    List<String> itemAttrsList = new ArrayList<>();
                    for (int j = 0; j < secordItemList.size(); j++) {
                        if (singleList.contains(secordItemList.get(j))) {
                            itemAttrsList.add(secordItemList.get(j));
                        }
                    }
                    compareOtherList.add(itemAttrsList);
                }
                return getListStrings(compareOtherList);
            }

            @NonNull
            private List<String> getSingleList(String attrKey) {
                int indexInList = DataUtil.indexInList(attrKeyList, attrKey);
                List<String> singleList = new ArrayList<>();
                List<AttrItemBean> attrItemBeens = itemAttrList.get(indexInList);
                for (int j = 0; j < attrItemBeens.size(); j++) {
                    AttrItemBean itemBean = attrItemBeens.get(j);
                    singleList.add(itemBean.getAttrId());
                }
                return singleList;
            }

            private void getItemClickChangePic() {
                if (selectAttrMap != null && selectAttrMap.size() > 0) {
                    List<String> listId = new ArrayList<>();
                    for (String strKey : selectAttrMap.keySet()) {
                        AttrItemBean itemBean = selectAttrMap.get(strKey);
                        listId.add(itemBean.getAttrId());
                    }
                    List<GoodsAttrCollections> collectioneList = new ArrayList<>();
                    for (GoodsAttrCollections goodAttr : attrCollectionses) {
                        List<String> attrs = goodAttr.getAttrs();
                        if (attrs.containsAll(listId)) {
                            collectioneList.add(goodAttr);
                        }
                    }
                    if (collectioneList.get(0).getInnerprice() != null && !"0".equals(collectioneList.get(0).getInnerprice())&&
                            collectioneList.get(0).getRedbean()!=null&&!collectioneList.get(0).getRedbean().equals("0")) {
                        tv_price.setText(collectioneList.get(0).getInnerprice() + "美豆");
                        tv_redprice.setText("+"+collectioneList.get(0).getRedbean()+"红豆");
                    } else if(collectioneList.get(0).getInnerprice().equals("0")&&!collectioneList.get(0).getRedbean().equals("0")){
                        tv_price.setText("");
                        tv_redprice.setText(collectioneList.get(0).getRedbean()+"红豆");
                    }else if (collectioneList.get(0).getRedbean().equals("0")&&!collectioneList.get(0).getInnerprice().equals("0")){
                        tv_price.setText(collectioneList.get(0).getInnerprice()+"美豆");
                        tv_redprice.setText("");
                    }else {
                        tv_price.setText("");
                        tv_redprice.setText("");
                    }

                    if (collectioneList.get(0).getStocknum() != null && !"".equals(collectioneList.get(0).getStocknum())) {
                        tvInventory.setText("库存:" + collectioneList.get(0).getStocknum() + "件");
                    } else {
                        tvInventory.setText("库存:0件");
                    }
                    Glide.with(context).load(Url.IMG_URL + collectioneList.get(0).getThumbnail()).placeholder(R.mipmap.iv_eg).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivImg);
                } else {
                    Glide.with(context).load(Url.IMG_URL + goodsInfo.getImages().get(0)).placeholder(R.mipmap.iv_eg).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivImg);
                    tvInventory.setText("库存:999件");
                }
            }

            @NonNull
            private List<String> getOnlyOneAttrCanSelect(AttrItemBean attrItemBean, String selectKey) {
                ArrayList<String> canSelects = getItemCanSelectAttr(attrItemBean);
                List<String> oneSelectCanAttr = new ArrayList<>();
                List<String> canAttrs = new ArrayList<>();
                for (String str : mapAllAttrs.keySet()) {
                    if (str.equals(selectKey)) {
                        List<AttrItemBean> attrItemBeenList = mapAllAttrs.get(str);
                        for (int j = 0; j < attrItemBeenList.size(); j++) {
                            oneSelectCanAttr.add(attrItemBeenList.get(j).getAttrId());
                        }
                    }
                }
                oneSelectCanAttr.addAll(canSelects);
                Set set = new HashSet();
                for (String str : oneSelectCanAttr) {
                    if (set.add(str)) {
                        canAttrs.add(str);  //去重后的可选的属性
                    }
                }
                return canAttrs;
            }

            @NonNull
            private List<String> getAllAlreadItemCanSelect(Map<String, AttrItemBean> selectAttrMap) {
                List<String> temporaryAttrId = new ArrayList<>();
                for (String str : selectAttrMap.keySet()) {
                    AttrItemBean attrBean = selectAttrMap.get(str);
                    temporaryAttrId.add(attrBean.getAttrId());
                }
                List<List<String>> collectionses = new ArrayList<>();
                for (GoodsAttrCollections goodAttr : attrCollectionses) {
                    List<String> attrs = goodAttr.getAttrs();
                    if (attrs.containsAll(temporaryAttrId)) {
                        collectionses.add(attrs);
                    }
                }
//                referList.addAll(collectionses.get(0));
//                for (int j = 0; j < collectionses.size(); j++) {
//                    referList.retainAll(collectionses.get(j));    //多数组取交集
//                }
                List<String> referList = getListStrings(collectionses);
                return referList;
            }

            @NonNull
            private List<String> getListStrings(List<List<String>> collectionses) {
                List<String> referList = new ArrayList<>();
                Set set = new HashSet();
                for (int i = 0; i < collectionses.size(); i++) {
                    List<String> list = collectionses.get(i);
                    for (int j = 0; j < list.size(); j++) {
                        if (set.add(list.get(j))) {
                            referList.add(list.get(j));
                        }
                    }
                }
                return referList;
            }

            @NonNull
            private ArrayList<String> getItemCanSelectAttr(AttrItemBean attrItemBean) {
                List<List<String>> collectionses = new ArrayList<>();
                for (GoodsAttrCollections goodAttr : attrCollectionses) {
                    if (goodAttr.getAttrs().contains(attrItemBean.getAttrId())) {
                        collectionses.add(goodAttr.getAttrs());
                    }
                }
                Set set = new HashSet();
                ArrayList<String> canSelects = new ArrayList<>();
                for (List<String> collection : collectionses) {
                    for (String attr : collection) {
                        if (set.add(attr)) {
                            canSelects.add(attr);
                        }
                    }
                }
                return canSelects;
            }
        };
        popupWindow_view = getLayoutInflater().inflate(R.layout.change_base_cart_info, null);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        ivImg = (ImageView) popupWindow_view.findViewById(R.id.ivImg);
        ImageView ivCancel = (ImageView) popupWindow_view.findViewById(R.id.ivCancel);
        TextView tvName = (TextView) popupWindow_view.findViewById(R.id.tvName);
        tvInventory = (TextView) popupWindow_view.findViewById(R.id.tvInventory);
        tv_price = (TextView) popupWindow_view.findViewById(R.id.tv_reward_price);
        tv_redprice= (TextView) popupWindow_view.findViewById(R.id.tv_reward_redprice);
        TextView tvAdd = (TextView) popupWindow_view.findViewById(R.id.tvAdd);
        TextView tvSub = (TextView) popupWindow_view.findViewById(R.id.tvSub);
        final EditText etNum = (EditText) popupWindow_view.findViewById(R.id.etNum);
        TextView tvSure_attr = (TextView) popupWindow_view.findViewById(R.id.tvSure_attr);
        ListView lvList = (ListView) popupWindow_view.findViewById(R.id.lvList);
        final LinearLayout type1 = (LinearLayout) popupWindow_view.findViewById(R.id.cart_get_type1);  //当面付
        final TextView tv1 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv1);
        final TextView tv11 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv11);
        final LinearLayout type2 = (LinearLayout) popupWindow_view.findViewById(R.id.cart_get_type2);   //自提
        final TextView tv2 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv2);
        final TextView tv22 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv22);
        final LinearLayout type3 = (LinearLayout) popupWindow_view.findViewById(R.id.cart_get_type3);   //邮寄
        final TextView tv3 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv3);
        final TextView tv33 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv33);
        TextView tv_amountofmail = (TextView) popupWindow_view.findViewById(R.id.tv_amountofmail);
        if (detailResult.getShopInfo().getAmountofmail() != null && !"".equals(detailResult.getShopInfo().getAmountofmail())) {
            if (!"0".equals(detailResult.getShopInfo().getAmountofmail())) {
                tv_amountofmail.setText("本店满" + detailResult.getShopInfo().getAmountofmail() + "红豆包邮");
                tv33.setText("(快递:" + goodsInfo.getPostage() + "红豆)");
            } else if (!DataUtil.moreThanZero(goodsInfo.getPostage())) {
                tv_amountofmail.setText("本店商品包邮");
                tv33.setText("(快递:0红豆)");
            } else {
                tv_amountofmail.setText("本店商品不包邮");
                tv33.setText("(快递:" + goodsInfo.getPostage() + "红豆)");
            }
        }

        RelativeLayout relative2 = (RelativeLayout) popupWindow_view.findViewById(R.id.relative2);
        WindowManager manger = (WindowManager) getSystemService(RewardCoinDetailActivity.WINDOW_SERVICE);
        Display display = manger.getDefaultDisplay();
        RelativeLayout rl_ctx = (RelativeLayout) popupWindow_view.findViewById(R.id.rl_ctx);
        ViewGroup.LayoutParams layoutParams = rl_ctx.getLayoutParams();
        layoutParams.height = 4 * display.getHeight() / 5;
        if (goodsInfo.getImages() != null && goodsInfo.getImages().size() > 0) {
            Glide.with(context).load(Url.IMG_URL + goodsInfo.getImages().get(0))
                    .placeholder(R.mipmap.iv_eg).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivImg);
        }
        tvName.setText(goodsInfo.getName());


        if (goodsInfo.getInnerprice() != null && !"0".equals(goodsInfo.getInnerprice())&&
                goodsInfo.getRedbeanprice()!=null&&!goodsInfo.getRedbeanprice().equals("0")) {
            tv_price.setText(goodsInfo.getInnerprice() + "美豆");
            tv_redprice.setText("+"+goodsInfo.getRedbeanprice()+"红豆");
        } else if(goodsInfo.getInnerprice().equals("0")&&!goodsInfo.getRedbeanprice().equals("0")){
            tv_price.setText("");
            tv_redprice.setText(goodsInfo.getRedbeanprice()+"红豆");
        }else if (goodsInfo.getRedbeanprice().equals("0")&&!goodsInfo.getInnerprice().equals("0")){
            tv_price.setText(goodsInfo.getInnerprice()+"美豆");
            tv_redprice.setText("");
        }else {
            tv_price.setText("");
            tv_redprice.setText("");
        }

        switch (goodsInfo.getGetermethod()) {
            case "1":  //邮寄
                DataUtil.noSelect(context, type1, tv1, tv11);
                DataUtil.noSelect(context, type2, tv2, tv22);
                DataUtil.canSelect(context, type3, tv3, tv33);
                stateType3 = false;
                type3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType3 = !stateType3;
                        if (stateType3) {
                            DataUtil.isSelect(context, type3, tv3, tv33);
                        } else {
                            DataUtil.canSelect(context, type3, tv3, tv33);
                        }
                    }
                });
                break;
            case "2":   //自提
                DataUtil.noSelect(context, type1, tv1, tv11);
                DataUtil.canSelect(context, type2, tv2, tv22);
                DataUtil.noSelect(context, type3, tv3, tv33);
                stateType2 = false;
                type2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType2 = !stateType2;
                        if (stateType2) {
                            DataUtil.isSelect(context, type2, tv2, tv22);
                        } else {
                            DataUtil.canSelect(context, type2, tv2, tv22);
                        }
                    }
                });
                break;
            case "3":   //邮寄+自提
                DataUtil.noSelect(context, type1, tv1, tv11);
                DataUtil.canSelect(context, type2, tv2, tv22);
                DataUtil.canSelect(context, type3, tv3, tv33);
                stateType2 = false;
                type2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType2 = !stateType2;
                        stateType3 = false;
                        if (stateType2) {
                            DataUtil.isSelect(context, type2, tv2, tv22);
                        } else {
                            DataUtil.canSelect(context, type2, tv2, tv22);
                        }
                        DataUtil.canSelect(context, type3, tv3, tv33);
                    }
                });
                stateType3 = false;
                type3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType3 = !stateType3;
                        stateType2 = false;
                        if (stateType3) {
                            DataUtil.isSelect(context, type3, tv3, tv33);
                        } else {
                            DataUtil.canSelect(context, type3, tv3, tv33);
                        }
                        DataUtil.canSelect(context, type2, tv2, tv22);
                    }
                });
                break;
            case "4":  //当面付
                DataUtil.noSelect(context, type2, tv2, tv22);
                DataUtil.noSelect(context, type3, tv3, tv33);
                stateType1 = false;
                type1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType1 = !stateType1;
                        if (stateType1) {
                            DataUtil.isSelect(context, type1, tv1, tv11);
                        } else {
                            DataUtil.canSelect(context, type1, tv1, tv11);
                        }
                    }
                });
                break;
            case "5":   //邮寄+当面付
                DataUtil.canSelect(context, type1, tv1, tv11);
                DataUtil.noSelect(context, type2, tv2, tv22);
                DataUtil.canSelect(context, type3, tv3, tv33);
                stateType1 = false;
                type1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType1 = !stateType1;
                        stateType3 = false;
                        if (stateType1) {
                            DataUtil.isSelect(context, type1, tv1, tv11);
                        } else {
                            DataUtil.canSelect(context, type1, tv1, tv11);
                        }
                        DataUtil.canSelect(context, type3, tv3, tv33);
                    }
                });
                stateType3 = false;
                type3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType3 = !stateType3;
                        stateType1 = false;
                        if (stateType3) {
                            DataUtil.isSelect(context, type3, tv3, tv33);
                        } else {
                            DataUtil.canSelect(context, type3, tv3, tv33);
                        }
                        DataUtil.canSelect(context, type1, tv1, tv11);
                    }
                });
                break;
            case "6":   //自提+当面付
                DataUtil.canSelect(context, type1, tv1, tv11);
                DataUtil.canSelect(context, type2, tv2, tv22);
                DataUtil.noSelect(context, type3, tv3, tv33);
                stateType1 = false;
                type1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType1 = !stateType1;
                        stateType2 = false;
                        if (stateType1) {
                            DataUtil.isSelect(context, type1, tv1, tv11);
                        } else {
                            DataUtil.canSelect(context, type1, tv1, tv11);
                        }
                        DataUtil.canSelect(context, type2, tv2, tv22);
                    }
                });
                stateType2 = false;
                type2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType2 = !stateType2;
                        stateType1 = false;
                        if (stateType2) {
                            DataUtil.isSelect(context, type2, tv2, tv22);
                        } else {
                            DataUtil.canSelect(context, type2, tv2, tv22);
                        }
                        DataUtil.canSelect(context, type1, tv1, tv11);
                    }
                });
                break;
            case "7":  //邮寄+自提+当面付
                DataUtil.canSelect(context, type2, tv2, tv22);
                DataUtil.canSelect(context, type3, tv3, tv33);
                stateType1 = false;
                DataUtil.canSelect(context, type1, tv1, tv11);
                type1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType1 = !stateType1;
                        stateType2 = false;
                        stateType3 = false;
                        if (stateType1) {
                            DataUtil.isSelect(context, type1, tv1, tv11);
                        } else {
                            DataUtil.canSelect(context, type1, tv1, tv11);
                        }
                        DataUtil.canSelect(context, type2, tv2, tv22);
                        DataUtil.canSelect(context, type3, tv3, tv33);
                    }
                });
                stateType2 = false;
                type2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType2 = !stateType2;
                        stateType1 = false;
                        stateType3 = false;
                        if (stateType2) {
                            DataUtil.isSelect(context, type2, tv2, tv22);
                        } else {
                            DataUtil.canSelect(context, type2, tv2, tv22);
                        }
                        DataUtil.canSelect(context, type1, tv1, tv11);
                        DataUtil.canSelect(context, type3, tv3, tv33);
                    }
                });
                stateType3 = false;
                type3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType3 = !stateType3;
                        stateType1 = false;
                        stateType2 = false;
                        if (stateType3) {
                            DataUtil.isSelect(context, type3, tv3, tv33);
                        } else {
                            DataUtil.canSelect(context, type3, tv3, tv33);
                        }
                        DataUtil.canSelect(context, type1, tv1, tv11);
                        DataUtil.canSelect(context, type2, tv2, tv22);
                    }
                });
                break;
        }

        tvSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = etNum.getText().toString().trim();
                int num = Integer.parseInt(trim);
                if (num > 1) {
                    num--;
                } else {
                    showShortToast("最少购买一件");
                }
                etNum.setText(String.valueOf(num));
            }
        });
        tvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = etNum.getText().toString().trim();
                int num = Integer.parseInt(trim);
                if (num <= 100) {
                    num++;
                } else {
                    showShortToast("购买数量不能大于100");
                }
                etNum.setText(String.valueOf(num));
            }
        });

        //立即购买
        tvSure_attr.setOnClickListener(new View.OnClickListener() {
            private boolean containsAll;   //进入确认支付界面
            private boolean b;

            @Override
            public void onClick(View view) {
                if (stateType1 || stateType2 || stateType3) {
                    List<String> attrIdList = new ArrayList<>();
                    List<String> keySelect = new ArrayList<>();
                    List<String> itemAttrs = new ArrayList<>();
                    String jsonAttrId = "[";     //  {"password":"1234","username":"cxl"}
                    for (String attr : selectAttrMap.keySet()) {
                        AttrItemBean s = selectAttrMap.get(attr);
                        keySelect.add(attr);
                        attrIdList.add(s.getAttrId());
                        itemAttrs.add(s.getName());
                        jsonAttrId = jsonAttrId + "\"" + s.getAttrId() + "\",";
                    }
                    String json = jsonAttrId.substring(0, jsonAttrId.length() - 1) + "]";
                    if (allList != null && allList.size() > 0) {
                        for (int i = 0; i < allList.size(); i++) {
                            AttrsSelect attrsSelect = allList.get(i);
                            Map<String, List<String>> map = attrsSelect.getItemMaps();
                            List<String> mapList = new ArrayList<>();
                            List<String> mapAttrId = new ArrayList<>();
                            for (String attr2 : map.keySet()) {
                                mapList.add(attr2);
                                List<String> list = map.get(attr2);
                                mapAttrId.addAll(list);
                            }
                            b = DataUtil.equalList(keySelect, mapList);
                            containsAll = mapAttrId.containsAll(attrIdList);
                            if (b && containsAll) {
                                String trim = tvInventory.getText().toString().trim();
                                String substring = trim.substring(trim.indexOf(":") + 1, trim.length() - 1);
                                if (DataUtil.moreThanZero(substring)) {
                                    popupWindow.dismiss();
                                    attrsSelect.setName(goodsInfo.getName());
                                    attrsSelect.setGoodsnum(etNum.getText().toString().trim());
                                    attrsSelect.setPostage(goodsInfo.getPostage());
                                    attrsSelect.setGetermethod(goodsInfo.getGetermethod());
                                    attrsSelect.setAttrlist(json);
                                    Log.d("flag", "onClick: "+json);
                                    attrsSelect.setItemGoodAttrs(itemAttrs);
                                    Intent intent = new Intent(context, ExchangePayActivity.class);
                                    intent.putExtra("attrs", attrsSelect);
                                    if (stateType2) {
                                        intent.putExtra("post", 0);  // 自提
                                    } else if (stateType3) {
                                        intent.putExtra("post", 1);  // 邮寄
                                    } else if (stateType1) {
                                        intent.putExtra("post", 2);  // 同城免邮
                                    }
                                    startActivity(intent);
                                    return;
                                } else {
                                    showShortToast("库存不足,无法支付");
                                }
                            }
                        }
                    }
                    if (!(b && containsAll)) {
                        showShortToast("请把该商品属性选完整");
                    }
                }  else {
                    showShortToast("请选择支付方式");
                }

            }
        });

        if (attr != null && !"".equals(attr)) {
            Iterator<String> keys = attr.keys();
            List<String> keyList = new ArrayList<>();
            itemAttrList = new ArrayList<>();
            mapAllAttrs = new HashMap<>();
            while (keys.hasNext()) {
                String next = keys.next();
                keyList.add(next);
                JSONArray jsonArray = attr.optJSONArray(next); //  [ ["十边形","att2929593f9c024ddd5"], ["六边形","att7364593f9960eb35b"] ]
                List<AttrItemBean> itemList = new ArrayList<>();
                for (int k = 0; k < jsonArray.length(); k++) {
                    try {
                        JSONArray jsonAllItemArray = (JSONArray) jsonArray.get(k);
                        AttrItemBean attrItemBean = new AttrItemBean();
                        for (int l = 0; l < jsonAllItemArray.length(); l++) {
                            if (l == 0) {
                                String attrName = (String) jsonAllItemArray.get(l);
                                attrItemBean.setName(attrName);
                            } else if (l == 1) {
                                String attrId = (String) jsonAllItemArray.get(l);
                                attrItemBean.setAttrId(attrId);
                            }
                            attrItemBean.setStates("1");
                        }
                        itemList.add(attrItemBean);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                itemAttrList.add(itemList);
                mapAllAttrs.put(next, itemList);
            }
            if (keyList != null && keyList.size() > 0 && detailResult.getGoodsAttrCollection() != null &&
                    detailResult.getGoodsAttrCollection().size() > 0) {
                coinPostGoodAttrAdapter = new CoinPostGoodAttrAdapter(context, handler, keyList, itemAttrList);
                lvList.setAdapter(coinPostGoodAttrAdapter);
                coinPostGoodAttrAdapter.notifyDataSetChanged();
            }
        }
        //消失
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    isRemove = false;
                    popupWindow = null;
                }
            }
        });
        if (!popupWindow.isShowing()) {
            isRemove = false;
        }
        popupWindow_view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int[] location = new int[2];
        linearBottom.getLocationOnScreen(location);
        popupWindow.showAtLocation(linearBottom, Gravity.BOTTOM, location[0], location[1] - popupWindow.getHeight());
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().setAttributes(lp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (popupWindow.isShowing())
            popupWindow.dismiss();

        super.onDestroy();
    }

    /**
     * 弹出分享界面
     */
    private void initPopuWindow() {
        popupWindow_view = getLayoutInflater().inflate(R.layout.pop_shared, null, false);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(clearWeedDetailShare, Gravity.BOTTOM, 0, 0);
        TextView tv_cancle = (TextView) popupWindow_view.findViewById(R.id.tv_cancle);
        LinearLayout ll_qq = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qq);
        LinearLayout ll_wechat = (LinearLayout) popupWindow_view.findViewById(R.id.ll_wechat);
        LinearLayout ll_qzone = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qzone);
        LinearLayout ll_friendscircle = (LinearLayout) popupWindow_view.findViewById(R.id.ll_friendscircle);
        View.OnClickListener shareClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_qq:
                        platform = SHARE_MEDIA.QQ;
                        break;
                    case R.id.ll_wechat:
                        platform = SHARE_MEDIA.WEIXIN;
                        break;
                    case R.id.ll_qzone:
                        platform = SHARE_MEDIA.QZONE;
                        break;
                    case R.id.ll_friendscircle:
                        platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                        break;
                }
                new ShareAction(ClearWeedDetailActivity.this).setPlatform(platform).setCallback(umShareListener).withTitle("正常消费，额外再获一倍奖励=免费消费").withMedia(new UMImage(ClearWeedDetailActivity.this, R.mipmap.logo))
                        .withText("推荐一个好商品;超级优惠,不用现金美豆即可抵钱花!").withTargetUrl(Url.IMG_URL + "/Home/pars/inner_get_url?id=" + id)
                        .share();
                popupWindow.dismiss();
            }
        };
        ll_qq.setOnClickListener(shareClickListener);
        ll_wechat.setOnClickListener(shareClickListener);
        ll_qzone.setOnClickListener(shareClickListener);
        ll_friendscircle.setOnClickListener(shareClickListener);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                showShortToast("收藏成功啦");
            } else {
                showShortToast("分享成功啦");
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            showShortToast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showShortToast("分享取消了");
        }
    };

    private void mapNavi() {
        activityList.add(this);
        // 打开log开关
        BNOuterLogUtil.setLogSwitcher(true);
        if (initDirs()) {
            initNavi();
        }
    }

    /**
     * 获取目录
     *
     * @return
     */
    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    private boolean hasBasePhoneAuth() {
        PackageManager pm = getPackageManager();
        for (String auth : authBaseArr) {
            if (pm.checkPermission(auth, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private void initNavi() {

        BNOuterTTSPlayerCallback ttsCallback = null;

        if (android.os.Build.VERSION.SDK_INT >= 23) {

            if (!hasBasePhoneAuth()) {

                requestPermissions(authBaseArr, authBaseRequestCode);
                return;

            }
        }

        BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
                if (0 == status) {
//                    authinfo = "key校验成功!";
                } else {
//                    authinfo = "key校验失败, " + msg;
                }
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
//                        Toast.makeText(context, authinfo, Toast.LENGTH_LONG).show();
                    }
                });
            }

            public void initSuccess() {
//                Toast.makeText(context, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                initSetting();


            }

            public void initStart() {
//                Toast.makeText(context, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
            }

            public void initFailed() {
//                Toast.makeText(context, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
            }


        }, null, ttsHandler, ttsPlayStateListener);

    }

    private void initSetting() {
        // 设置是否双屏显示
        BNaviSettingManager.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        // 设置导航播报模式
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // 是否开启路况
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);

        Bundle bundle = new Bundle();
        // 必须设置APPID，否则会静音
        bundle.putString(BNCommonSettingParam.TTS_APP_ID, Constants.BAIDUMAP_ID);
        BNaviSettingManager.setNaviSdkParam(bundle);


    }

    private boolean hasCompletePhoneAuth() {
        PackageManager pm = getPackageManager();
        for (String auth : authComArr) {
            if (pm.checkPermission(auth, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private BNRoutePlanNode.CoordinateType mCoordinateType = null;

    private void routeplanToNavi(BNRoutePlanNode.CoordinateType coType) {
        mCoordinateType = coType;
        // 权限申请
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            // 保证导航功能完备
            if (!hasCompletePhoneAuth()) {
                if (!hasRequestComAuth) {
                    hasRequestComAuth = true;
                    requestPermissions(authComArr, authComRequestCode);
                    return;
                }
            }

        }
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        switch (coType) {
            case BD09LL: {
                sNode = new BNRoutePlanNode(Double.parseDouble(MyApplication.getInstance().getLongitude()), Double.parseDouble(MyApplication.getInstance().getLatitude()), "我的位置", null, coType);
                eNode = new BNRoutePlanNode(Double.parseDouble(shopInfo.getLongitude()), Double.parseDouble(shopInfo.getDimensions()), shopInfo.getName(), null, coType);
                break;
            }
        }
        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);
            BaiduNaviManager.getInstance().launchNavigator(this, list, 1, true, new ClearWeedDetailActivity.DemoRoutePlanListener(sNode));
        }
    }

    public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            /*
             * 设置途径点以及resetEndNode会回调该接口
			 */

            for (Activity ac : activityList) {

                if (ac.getClass().getName().endsWith("MapNaviActivity")) {

                    return;
                }
            }
            Intent intent = new Intent(context, MapNaviActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ROUTE_PLAN_NODE, mBNRoutePlanNode);
            intent.putExtras(bundle);
            intent.putExtra("type", "6");
            startActivity(intent);

        }

        @Override
        public void onRoutePlanFailed() {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            Toast.makeText(context, "导航失败", Toast.LENGTH_SHORT).show();
        }
    }

}
